import UploadFile from '@/components/UploadExcel/index';
import DriveParaCalcCommon from '@/pages/drivepara/driveParaCalcCommon';
import { downloadTemplateByName } from '@/services/baseData/fileData';
import { EllipsisOutlined } from '@ant-design/icons';
import type { ReactText } from 'react';
import { userList } from '@/services/login/login';
import { licenseOrderList } from '@/services/sales/licenseOrder';
import {
  addAfterSalesNeedInfoEx,
  addTempAfterSalesNeedInfoEx,
  afterSalesDetailExport,
  getAfterSalesNeedInfoDetailById,
  getS210motorList,
  getV90motorList,
  roleUserList,
  sendAdminReminder,
  updateAfterSalesNeedInfoEx,
  updateChiefEngineer,
  updateEngineer,
  updateTempAfterSalesNeedInfoEx,
} from '@/services/sales/salesNeedInfo';
import { CloseCircleOutlined, PlusOutlined } from '@ant-design/icons';
import type { EditableFormInstance, ProColumns, ProFormInstance } from '@ant-design/pro-components';
import {
  ProFormDigit,
  ProCard,
  ProFormList,
  ProFormGroup,
  ProFormDependency,
} from '@ant-design/pro-components';
import { ProList } from '@ant-design/pro-list';
import ProForm, { ProFormSelect, ProFormText } from '@ant-design/pro-form';
import { FooterToolbar, PageHeaderWrapper } from '@ant-design/pro-layout';
import {
  Button,
  Card,
  Col,
  Space,
  Form,
  Input,
  InputNumber,
  message,
  Modal,
  Popover,
  Row,
  Select,
  Steps,
  Progress,
  Tag,
} from 'antd';

import React, { useEffect, useRef, useState } from 'react';
import { history, useAccess, useLocation, useModel } from 'umi';
import styles from './style.less';

import DebounceSelect from '@/components/DebounceSelect';

import { EditableProTable } from '@ant-design/pro-table';
const { Step } = Steps;
import type { FormLayout } from 'antd/es/form/Form';
import SalesNeedInfoDescription from '@/components/DriveParaCalc/salesNeedInfoDescription';
// 需要在切换不同状态的时候置空
const rowNullData = {
  motorId: null, //电机ID
  ratedCurrent: null, //额定电流(A)
  ratedTorque: null, //额定扭矩(Nm)
  ratedPower: null, //额定功率(KW)
  ecoderType: null, //编码器
  brake: null, //抱闸
  ratedSpeed: null, //额定速度(rpm)
  ratedVoltage: null, //额定电压(V)
  motorInertia: null, //电机惯量(10^-4kg·cm2)
};

interface TableFormDateType {
  id: string;
  workId?: string;
  name?: string;
  department?: string;
  isNew?: boolean;
  editable?: boolean;
}
const fieldLabels = {
  name: '仓库名',
  url: '仓库域名',
  owner: '仓库管理员',
  approver: '审批人',
  dateRange: '生效日期',
  type: '仓库类型',
  name2: '任务名',
  url2: '任务描述',
  owner2: '执行人',
  approver2: '责任人',
  dateRange2: '生效日期',
  type2: '任务类型',
};
interface UserValue {
  label: string;
  value: string;
}

async function fetchV90motorList(username: string): Promise<UserValue[]> {
  console.log('fetching user', username);
  return getV90motorList({ blurry: username }).then((res) => {
    res.data.push({ motorOrderNum: '第三方', id: '第三方' });
    console.log(res, '---res---');
    return res.data.map((item) => {
      return {
        key: item.id,
        label: item.motorOrderNum,
        value: item.motorOrderNum,
        rowData: item,
      };
    });
  });
}

async function fetchS210motorList(username: string): Promise<UserValue[]> {
  console.log('fetching user', username);
  return getS210motorList({ blurry: username }).then((res) => {
    res.data.push({ motorOrderNum: '第三方', id: '第三方' });
    return res.data.map((item) => {
      return {
        key: item.id,
        label: item.motorOrderNum,
        value: item.motorOrderNum,
        rowData: item,
      };
    });
  });
}

async function roleUsers(username: string, roleCode: string): Promise<UserValue[]> {
  console.log('fetching user', username);
  return roleUserList({ blurry: username, roleCode: roleCode }).then((res) => {
    return res.data.map((item) => {
      return {
        key: item.id,
        label: item.name,
        value: item.id,
        rowData: item,
      };
    });
  });
}
const LAYOUT_TYPE_HORIZONTAL = 'horizontal';
const SalesNeedInfoDetail: React.FC<{}> = () => {
  // const params = useParams();
  const location = useLocation();
  // console.log(params, '---ceshi---');
  const [errorStatus, SetErrorStatus] = useState(false); //显示上传预览

  const [showUploadFile, SetShowUploadFile] = useState(false); //显示上传预览
  const [stackerShowUploadFile, SetStackerShowUploadFile] = useState(false); //显示上传预览
  const editorFormRef = useRef<EditableFormInstance<DataSourceType>>();
  // 表格数据
  const [dataSource, setDataSource] = useState<DataSourceType[]>([]);
  const [v90Select, setV90Select] = useState(false); //选择了v90
  const [thirdSelect, setThirdSelect] = useState(false); //选择了第三方

  const [formDisabled, setFormDisabled] = useState(false); //设置表单禁用

  const [detailStatus, setDetailStatus] = useState(0); //设置表单禁用

  const [assignDesc, setAssignDesc] = useState('客户未提交设备信息');
  const [chiefEngineerDesc, setChiefEngineerDesc] = useState('主任工程师');
  const [engineerDesc, setEngineerDesc] = useState('工程师');

  const [engineerStatus, setEngineerStatus] = useState(1); //设置表单禁用
  const [roleUserTitle, setRoleUserTitle] = useState('主任工程师');
  const [roleUserVisit, setRoleUserVisit] = useState(false);
  const [confirmLoading, setConfirmLoading] = useState(false); //编辑框的disable
  const [engineerDisabled, setEngineerDisabled] = useState(false); // 设置其他工程师禁用
  const access = useAccess(); // access 实例的成员: canReadFoo, canUpdateFoo, canDeleteFoo
  const [checked, setChecked] = useState(false);
  const driveRef = useRef(null);
  const [form] = Form.useForm();

  const [driveCommonVis, setDriveCommonVis] = useState(false);

  const [values, setValues] = useState({});
  const [grid, setGrid] = useState(true);
  // form表单的初始化的值
  const [formInit, setFormInit] = useState({});
  const [formLayoutType, setFormLayoutType] = useState<FormLayout>(LAYOUT_TYPE_HORIZONTAL);
  // 个人用户数据
  let user = {};
  let deviceInfo = {};

  const { initialState } = useModel('@@initialState');
  const { currentUser } = initialState || {};

  // ProList
  const [expandedRowKeys, setExpandedRowKeys] = useState<readonly ReactText[]>([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<ReactText[]>([]);
  const rowSelection = {
    selectedRowKeys,
    onChange: (keys: ReactText[]) => setSelectedRowKeys(keys),
  };
  const [dataSourceTwo, setDataSourceTwo] = useState<any[]>([]);

  const [axiosCreate, setAxiosCreate] = useState<Boolean>(false);

  const actionRef = useRef<ActionType>();

  const stackerDriveTypeMap = new Map([
    [1, 'G120 CU250S-2'],
    [2, 'G120 CU240E-2'],
    [3, 'G120C'],
    [4, 'S120 CU320-2'],
    [5, 'S120 CU310-2'],
    [6, 'V90'],
    [0, 'Others'],
  ]);

  const stackerControlModeMap = new Map([
    [1, 'Epos定位'],
    [2, '速度闭环控制'],
    [3, '无编码器矢量控制'],
    [4, 'V/F'],
  ]);

  const motorManufacturerMap = new Map([
    [1, 'SIEMENS'],
    [2, 'SEW'],
    [0, 'Others'],
  ]);

  const stackerMotorWiringMap = new Map([
    [1, '▲'],
    [2, 'Y'],
  ]);

  const stackerMotorBrakeMap = new Map([
    [0, '不带抱闸'],
    [1, '带抱闸'],
  ]);

  const stackerEncoderInterfaceMap = new Map([
    [1, '端子'],
    [2, 'D-Sub'],
  ]);

  const stackerSigPolarityMap = new Map([
    [1, '单极性'],
    [2, '双极性'],
  ]);

  const driveTypeMap = new Map([
    [1, 'V90'],
    [2, 'S210'],
  ]);

  const loadTypeMap = new Map([
    [1, '水平'],
    [2, '旋转'],
    [3, '垂直'],
    [4, '斜坡'],
    [5, '其它'],
  ]);

  const mechanicalStructureMap = new Map([
    [1, '丝杠'],
    [2, '齿轮齿条'],
    [3, '皮带轮'],
    [4, '圆盘'],
    [5, '辊式带'],
    [6, '链条'],
  ]);

  const controlModeMap = new Map([
    [1, 'TO'],
    [2, 'Epos'],
    [3, 'Speed'],
  ]);

  const commTelegramMap = new Map([
    [105, '105'],
    [111, '111'],
    [102, '102'],
    [3, '3'],
    [1, '1'],
  ]);

  const additionalTelegramMap = new Map([
    [999, 'None'],
    [750, '750'],
  ]);

  const timeMap = new Map([
    [1, '<0.05'],
    [2, '0.05-0.09'],
    [3, '0.1-0.2'],
    [4, '0.25-0.4'],
    [5, '0.45-0.9'],
    [6, '1.0-2.0'],
    [7, '2.0-4.0'],
    [8, '>4.0'],
  ]);



  /**
   * 设备版本
   */
  const [stackerType, setStackerType] = useState<Number>(1);

  const handleSubmit2 = async () => {
    setConfirmLoading(true);

    if (roleUserTitle == '主任工程师') {
      const result = await updateChiefEngineer({
        id: location.query.id,
        engineerId: form.getFieldValue('engineerId'),
      });
      setChiefEngineerDesc(result?.data?.name);
      setEngineerStatus(result?.data?.engineerStatus);
    } else {
      const result = await updateEngineer({
        id: location.query.id,
        engineerId: form.getFieldValue('engineerId'),
      });
      setEngineerDesc(result?.data?.name);
      setEngineerStatus(result?.data?.engineerStatus);
    }

    setConfirmLoading(false);
    setRoleUserVisit(false);
    message.success('添加成功');
    // actionRef.current.reset();
    // actionRef.current.reload();
    // actionRef.current.clearSelected();
    // setModalVisit(false);
  };

  const handleSubmit = async () => {};

  useEffect(() => {
    (async () => {
      // 相当于新建
      if (location.query.id !== undefined && location.query.id !== null) {
        const result = await getAfterSalesNeedInfoDetailById({ id: location.query.id });
        setFormDisabled(true);

        user = result?.data?.userEx;
        deviceInfo = result?.data?.deviceInfoEx;
        // console.log(detailStatus, "---detailStatus---");
        setDetailStatus(result?.data?.status);
        // if(detailStatus < result?.data?.status)
        // {
        //   setDetailStatus(result?.data?.status);
        // }
        if (result?.data?.status > 1) {
          setAssignDesc('客户已提交设备信息');
        }
        setEngineerStatus(result?.data?.engineerStatus || 1);

        setChiefEngineerDesc(result?.data?.chiefEngineerName);
        setEngineerDesc(result?.data?.engineerName);
        // console.log(currentUser?.loginName,"--currentUser?.loginName---");
        // console.log(result?.data?.engineerName, "---result?.data?.engineerName---");

        if (access.canEngineer() && currentUser?.loginName !== result?.data?.engineerName) {
          setEngineerDisabled(true);
        }
        setStackerType(deviceInfo?.stackerType);

        setFormInit({
          userId: { label: user?.name, value: user?.id },
          licensOrderId: {
            label: result?.data?.licenseOrderNum,
            value: result?.data?.licenseOrderNum,
          },
          licenseCount: result?.data?.licenseCount,
          driveName: deviceInfo?.deviceName,
          vm: deviceInfo?.vm,
          isProduction: deviceInfo?.production,
          plcType: deviceInfo?.plcType,
          stackerType: deviceInfo?.stackerType,
          hmiType: deviceInfo?.hmiType,
          trackLength: deviceInfo?.trackLength,
          liftingHeight: deviceInfo?.liftingHeight,
          forkOutLength: deviceInfo?.forkOutLength,
          stackerWeight: deviceInfo?.stackerWeight,
          platformWeight: deviceInfo?.platformWeight,
          loadWeight: deviceInfo?.loadWeight,
        });

        if (
          deviceInfo?.stackerType !== null &&
          deviceInfo?.stackerType > 10 &&
          deviceInfo?.stackerType < 19
        ) {
          setDataSourceTwo(result?.data?.stackerShaftInfoExes);
        } else {
          setDataSourceTwo(result?.data?.shaftInfoExList);
        }
        // formRef.current?.setFieldsValue({
        //   userId: { label: user?.name, value: user?.id },
        //   licensOrderId: {
        //     label: result?.data?.licenseOrderNum,
        //     value: result?.data?.licenseOrderNum,
        //   },
        //   licenseCount: result?.data?.licenseCount,
        //   driveName: deviceInfo?.deviceName,
        //   vm: deviceInfo?.vm,
        //   isProduction: deviceInfo?.production,
        //   plcType: deviceInfo?.plcType,
        // });
      }
    })();
  }, []);
  const formAdd = location.query.id === null || location.query.id === undefined ? true : false;

  /**
   * 穿梭框的数据设置
   */

  const formRef = useRef<
    ProFormInstance<{
      name: string;
      company?: string;
      useMode?: string;
    }>
  >();
  const columns: ProColumns[] = [
    {
      title: '序号',
      align: 'center',
      dataIndex: 'index',
      valueType: 'index',
      width: 40,
    },

    {
      title: '轴名称', //表头显示的名称
      search: false,
      align: 'center',
      dataIndex: 'shaftName', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
      width: 60,
    },

    {
      title: '硬件标识符', //表头显示的名称
      search: false,
      align: 'center',
      dataIndex: 'hardwareIdentifier', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
      width: 60,
      valueType: 'digit',
    },

    {
      title: '驱动类型',
      width: 60,
      search: false,
      align: 'center',
      key: 'driveType',
      dataIndex: 'driveType',
      valueType: 'select',
      valueEnum: {
        1: { text: 'V90', status: 'Default' },
        2: {
          text: 'S210',
          status: 'success',
        },
      },
    },

    {
      title: '电机订货号', //
      search: false,
      align: 'center',
      dataIndex: 'motorOrderNum',
      width: 100,
    },

    {
      title: '电机ID', //表头显示的名称
      width: 60,
      search: false,
      // align: 'center',
      dataIndex: 'motorId', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
      // valueType: 'digit',
      // editable: (_, text, record) => {
      //   console.log(_, text, record, '--editable-');
      //   return true;
      // },
    },
    {
      title: '额定电流(A)', //表头显示的名称
      width: 60,
      search: false,
      align: 'center',
      dataIndex: 'ratedCurrent',
    },
    {
      title: '额定扭矩(Nm)', //表头显示的名称
      width: 60,
      search: false,
      align: 'center',
      dataIndex: 'ratedTorque', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
      valueType: 'digit',
    },
    {
      title: '额定功率(KW)', //表头显示的名称
      width: 60,
      search: false,
      align: 'center',
      dataIndex: 'ratedPower',
      valueType: 'digit',
    },
    {
      title: '编码器', //表头显示的名称
      width: 80,
      search: false,
      align: 'center',
      dataIndex: 'ecoderType', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
      valueEnum: {
        0: '单圈绝对编码器',
        1: '多圈绝对编码器',
        2: '增量式编码器',
      },
      valueType: 'select',
    },

    {
      title: '抱闸', //表头显示的名称
      width: 60,
      search: false,
      align: 'center',
      dataIndex: 'brake',
      valueEnum: {
        0: '不带抱闸',
        1: '带抱闸',
      },
      valueType: 'select',
    },
    {
      title: '额定速度(rpm)', //表头显示的名称
      width: 60,
      search: false,
      align: 'center',
      dataIndex: 'ratedSpeed', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
    },
    {
      title: '额定电压(V)', //表头显示的名称
      width: 60,
      search: false,
      align: 'center',
      dataIndex: 'ratedVoltage',
    },
    {
      title: '电机惯量(10^-4kg·cm2)', //表头显示的名称
      width: 60,
      search: false,
      align: 'center',
      dataIndex: 'motorInertia', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
    },

    {
      title: '负载类型', //表头显示的名称
      width: 60,
      align: 'center',
      dataIndex: 'loadType',
      valueType: 'select',
      valueEnum: {
        1: { text: '水平' },
        2: { text: '旋转' },
        3: { text: '垂直' },
        4: { text: '斜坡' },
        5: { text: '其它' },
      },
    },

    {
      title: '机械结构', //表头显示的名称
      width: 60,
      search: false,
      align: 'center',
      dataIndex: 'mechanicalStructure',
      valueType: 'select',
      valueEnum: {
        1: { text: '丝杠' },
        2: { text: '齿轮齿条' },
        3: { text: '皮带轮' },
        4: { text: '圆盘' },
        5: { text: '辊式带' },
        6: { text: '链条' },
      },
    },
    {
      title: '控制模式', //表头显示的名称
      width: 60,
      search: false,
      align: 'center',
      dataIndex: 'controlMode', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
      valueType: 'select',
      valueEnum: (row) => {
        return {
          1: { text: 'TO' },
          2: { text: 'Epos' },
          3: { text: 'Speed' },
        };
      },
      initialValue: 1,
    },

    {
      title: '通讯报文', //表头显示的名称
      width: 60,
      search: false,
      align: 'center',
      dataIndex: 'commTelegram',
      valueType: 'select',
      valueEnum: {
        105: { text: '105' },
        111: { text: '111' },
        102: { text: '102' },
        3: { text: '3' },
        1: { text: '1' },
      },
      initialValue: 105,
    },

    {
      title: '附加报文', //表头显示的名称
      width: 60,
      search: false,
      align: 'center',
      dataIndex: 'additionalTelegram', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
      valueType: 'select',
      valueEnum: {
        999: { text: 'None' },
        750: { text: '750' },
      },
    },
    // {
    //   title: '电机方向', //表头显示的名称
    //   search: false,
    //   align: 'center',
    //   dataIndex: 'motorRotation',
    //   valueType: 'select',
    //   valueEnum: {
    //     0: { text: '正向' },
    //     1: { text: '反向' },
    //   },
    // },
    {
      title: '齿轮比电机(V90 EPOS)', //表头显示的名称
      search: false,
      align: 'center',
      width: 60,
      dataIndex: 'gearRationMotor',
    },
    {
      title: '齿轮比负载(V90 EPOS)', //表头显示的名称
      search: false,
      align: 'center',
      width: 60,
      dataIndex: 'gearRationLoad', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
    },

    {
      title: '负载一圈的距离(V90 EPOS) （mm/°）', //表头显示的名称
      search: false,
      align: 'center',
      width: 60,
      dataIndex: 'loadOneTurnDistance',
    },
    {
      title: '设备最大速度Vmax(V90 EPOS)（m/s）', //表头显示的名称
      search: false,
      align: 'center',
      width: 60,
      dataIndex: 'velocityMax',
    },

    {
      title: '0-Vmax时间(V90 EPOS) （s）', //表头显示的名称
      search: false,
      align: 'center',
      width: 80,
      dataIndex: 'increaseTimeEpos',
      valueType: 'select',
      valueEnum: {
        1: { text: '<0.05' },
        2: { text: '0.05-0.09' },
        3: { text: '0.1-0.2' },
        4: { text: '0.25-0.4' },
        5: { text: '0.45-0.9' },
        6: { text: '1.0-2.0' },
        7: { text: '2.0-4.0' },
        8: { text: '>4.0' },
      },
    },
    {
      title: 'Vmax-0时间(V90 EPOS) （s）', //表头显示的名称
      search: false,
      align: 'center',
      width: 80,
      dataIndex: 'decreaseTimeEpos', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
      valueType: 'select',
      valueEnum: {
        1: { text: '<0.05' },
        2: { text: '0.05-0.09' },
        3: { text: '0.1-0.2' },
        4: { text: '0.25-0.4' },
        5: { text: '0.45-0.9' },
        6: { text: '1.0-2.0' },
        7: { text: '2.0-4.0' },
        8: { text: '>4.0' },
      },
    },

    {
      title: '操作',
      width: 80,
      align: 'center',
      valueType: 'option',
      key: 'option',
      fixed: 'right',
      render: (text, record, _, action) => [
        <a
          key="editable"
          onClick={() => {
            action?.startEditable?.(record.id);
          }}
        >
          编辑
        </a>,
        <a
          key="delete"
          onClick={() => {
            setDataSource(dataSource.filter((item) => item.id !== record.id));
          }}
        >
          删除
        </a>,
        <a
          key="preView"
          onClick={() => {
            setDriveCommonVis(true);
            setValues(record);
          }}
        >
          预览
        </a>,
        <EditableProTable.RecordCreator
          key="copy"
          record={{
            ...record,
            id: (Math.random() * 1000000).toFixed(0),
          }}
        >
          <a>复制</a>
        </EditableProTable.RecordCreator>,
      ],
    },
  ];

  const stackerColumns: ProColumns[] = [
    {
      title: '序号',
      align: 'center',
      dataIndex: 'index',
      valueType: 'index',
      width: 40,
    },
    {
      title: '轴名称', //表头显示的名称
      search: false,
      align: 'center',
      dataIndex: 'shaftName', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
      width: 60,
    },
    {
      title: '最大速度',
      search: false,
      align: 'center',
      dataIndex: 'velocityMax',
      width: 60,
    },
    {
      title: '最大加速度',
      search: false,
      align: 'center',
      dataIndex: 'accelerationMax',
      width: 60,
    },
    {
      title: '齿轮比电机',
      search: false,
      align: 'center',
      dataIndex: 'gearRationMotor',
      width: 60,
    },
    {
      title: '齿轮比负载',
      search: false,
      align: 'center',
      dataIndex: 'gearRationLoad',
      width: 60,
    },
    {
      title: '负载一圈的距离(mm)',
      search: false,
      align: 'center',
      dataIndex: 'loadOneTurnDistance',
      width: 60,
    },
    {
      title: '驱动类型', //表头显示的名称
      width: 60,
      search: false,
      align: 'center',
      dataIndex: 'driveType',
      valueType: 'select',
      valueEnum: {
        1: { text: 'G120 CU250S-2' },
        2: { text: 'G120 CU240E-2' },
        3: { text: 'G120C' },
        4: { text: 'S120 CU320-2' },
        5: { text: 'S120 CU310-2' },
        6: { text: 'V90' },
        0: { text: 'Others' },
      },
    },
    {
      title: '控制模式', //表头显示的名称
      width: 60,
      search: false,
      align: 'center',
      dataIndex: 'controlMode',
      valueType: 'select',
      valueEnum: {
        1: { text: 'Epos定位' },
        2: { text: '速度闭环控制' },
        3: { text: '无编码器矢量控制' },
        4: { text: 'V/F' },
      },
    },
    {
      title: '电机厂家', //表头显示的名称
      width: 60,
      search: false,
      align: 'center',
      dataIndex: 'motorManufacturer',
    },
    {
      title: '电机订货号',
      search: false,
      align: 'center',
      dataIndex: 'motorOrderNum',
      width: 60,
    },
    {
      title: '电压(V)',
      search: false,
      align: 'center',
      dataIndex: 'motorVoltage',
      width: 60,
    },
    {
      title: '接线', //表头显示的名称
      width: 60,
      search: false,
      align: 'center',
      dataIndex: 'motorWiring',
      valueType: 'select',
      valueEnum: {
        1: { text: '' },
        2: { text: 'Y' },
      },
    },
    {
      title: '功率(kw)',
      search: false,
      align: 'center',
      dataIndex: 'motorPower',
      width: 60,
    },
    {
      title: '力矩（伺服）(Nm)',
      search: false,
      align: 'center',
      dataIndex: 'motorTorque',
      width: 60,
    },
    {
      title: '电流(A)',
      search: false,
      align: 'center',
      dataIndex: 'motorCurrent',
      width: 60,
    },
    {
      title: '速度(rpm)',
      search: false,
      align: 'center',
      dataIndex: 'motorSpeed',
      width: 60,
    },
    {
      title: '功率因数',
      search: false,
      align: 'center',
      dataIndex: 'motorPowerFactor',
      width: 60,
    },
    {
      title: '频率(Hz)',
      search: false,
      align: 'center',
      dataIndex: 'motorFrequency',
      width: 60,
    },
    {
      title: '抱闸', //表头显示的名称
      width: 60,
      search: false,
      align: 'center',
      dataIndex: 'motorBrake',
      valueType: 'select',
      valueEnum: {
        0: { text: '不带抱闸' },
        1: { text: '带抱闸' },
      },
    },
    {
      title: '工作时电机接线方式', //表头显示的名称
      width: 60,
      search: false,
      align: 'center',
      dataIndex: 'workMotorWiring',
      valueType: 'select',
      valueEnum: {
        1: { text: '▲' },
        2: { text: 'Y' },
      },
    },
    {
      title: '电机编码器接口', //表头显示的名称
      width: 60,
      search: false,
      align: 'center',
      dataIndex: 'motorEncoderInterface',
      valueType: 'select',
      valueEnum: {
        1: { text: '端子' },
        2: { text: 'D-Sub' },
      },
    },
    {
      title: '电机编码器类型',
      search: false,
      align: 'center',
      dataIndex: 'motorEncoderType',
      width: 60,
    },
    {
      title: '电机编码器信号极性', //表头显示的名称
      width: 60,
      search: false,
      align: 'center',
      dataIndex: 'motorEncoderSigPolarity',
      valueType: 'select',
      valueEnum: {
        1: { text: '单极性' },
        2: { text: '双极性' },
      },
    },
    {
      title: '位置编码器厂家', //表头显示的名称
      width: 60,
      search: false,
      align: 'center',
      dataIndex: 'posEncoderManufacturer',
    },
    {
      title: '位置编码器型号',
      search: false,
      align: 'center',
      dataIndex: 'posEncoderType',
      width: 60,
    },
    {
      title: '位置编码器接口', //表头显示的名称
      width: 60,
      search: false,
      align: 'center',
      dataIndex: 'posEncoderInterface',
      valueType: 'select',
      valueEnum: {
        1: { text: '端子' },
        2: { text: 'D-Sub' },
      },
    },
  ];

  const [error, setError] = useState<ErrorField[]>([]);
  const getErrorInfo = (errors: ErrorField[]) => {
    // return null;
    const errorCount = errors.filter((item) => item.errors.length > 0).length;

    if (!errors || errorCount === 0) {
      return null;
    }
    const scrollToField = (fieldKey: string) => {
      const labelNode = document.querySelector(`label[for="${fieldKey}"]`);
      if (labelNode) {
        labelNode.scrollIntoView(true);
      }
    };
    const errorList = errors.map((err) => {
      if (!err || err.errors.length === 0) {
        return null;
      }
      const key = err.name[0] as string;
      return (
        <li key={key} className={styles.errorListItem} onClick={() => scrollToField(key)}>
          <CloseCircleOutlined className={styles.errorIcon} />
          <div className={styles.errorMessage}>{err.errors[0]}</div>
          <div className={styles.errorField}>{fieldLabels[key]}</div>
        </li>
      );
    });
    return (
      <span className={styles.errorIcon}>
        <Popover
          title="表单校验信息"
          content={errorList}
          overlayClassName={styles.errorPopover}
          trigger="click"
          getPopupContainer={(trigger: HTMLElement) => {
            if (trigger && trigger.parentNode) {
              return trigger.parentNode as HTMLElement;
            }
            return trigger;
          }}
        >
          <CloseCircleOutlined />
        </Popover>
        {errorCount}
      </span>
    );
  };

  const onFinish = async (values: Record<string, any>) => {
    // setError([]);
    console.log(values, dataSource, '---tijiao-1212121---');
    if (stackerType !== null && stackerType < 10 && values.licenseCount !== dataSourceTwo.length) {
      message.error('驱动数量和轴数量不一致重新填写');
      return;
    }
    // if (stackerType !== null && stackerType > 10 && stackerType < 19 && dataSourceTwo.length === 0) {
    //   message.error('请填写轴信息');
    //   return;
    // }
    try {
      // 新增
      let result = null;

      if (!formDisabled) {
        if (stackerType !== null && stackerType > 10 && stackerType < 19) {
          result = await addAfterSalesNeedInfoEx({
            userId: values.userId.value,
            driveName: values.driveName,
            stackerType: stackerType,
            hmiType: values.hmiType,
            trackLength: values.trackLength,
            liftingHeight: values.liftingHeight,
            forkOutLength: values.forkOutLength,
            stackerWeight: values.stackerWeight,
            platformWeight: values.platformWeight,
            loadWeight: values.loadWeight,
            plcType: values.plcType,
            vm: values.vm,
            licenseOrderNum: values.licensOrderId.label,
            licenseCount: values.licenseCount,
            stackerShaftInfoExes: dataSourceTwo,
          });
        } else {
          result = await addAfterSalesNeedInfoEx({
            userId: values.userId.value,
            stackerType: stackerType,
            driveName: values.driveName,
            isProduction: values.isProduction,
            plcType: values.plcType,
            vm: values.vm,
            licenseOrderNum: values.licensOrderId.label,
            licenseCount: values.licenseCount,
            shaftInfoExDtoList: dataSourceTwo,
          });
          console.log(result, "---result-----");
        }
      } else {
        // 更新
        if (stackerType !== null && stackerType > 10 && stackerType < 19) {
          result = await updateAfterSalesNeedInfoEx({
            id: location.query.id,
            userId: values.userId.value,
            stackerType: stackerType,
            driveName: values.driveName,
            hmiType: values.hmiType,
            trackLength: values.trackLength,
            liftingHeight: values.liftingHeight,
            forkOutLength: values.forkOutLength,
            stackerWeight: values.stackerWeight,
            platformWeight: values.platformWeight,
            loadWeight: values.loadWeight,
            plcType: values.plcType,
            vm: values.vm,
            licenseOrderNum: values.licensOrderId.label,
            licenseCount: values.licenseCount,
            stackerShaftInfoExes: dataSourceTwo,
          });
        } else {
          result = await updateAfterSalesNeedInfoEx({
            id: location.query.id,
            userId: values.userId.value,
            driveName: values.driveName,
            stackerType: stackerType,
            isProduction: values.isProduction,
            plcType: values.plcType,
            vm: values.vm,
            licenseOrderNum: values.licensOrderId.label,
            licenseCount: values.licenseCount,
            shaftInfoExDtoList: dataSourceTwo,
          });
          console.log(result, "---result-----");
        }
      }

      if (result !== null && result !== undefined) {
        await sendAdminReminder(result.data.id);
        message.success('添加成功');

        history.push({
          pathname: `/sales/salesNeedInfoCustomer`,
        });
      }
    } catch {
      // console.log
    }
  };
  const onTempSave = async () => {
    console.log(formRef.current?.getFieldsFormatValue?.(), '---');

    formRef.current?.validateFieldsReturnFormatValue?.().then(async (values) => {
      try {
        // 新增
        let result = null;
        console.log(values, "---values---");
        console.log(dataSourceTwo, "---dataSourceTwo---");
        debugger

        if (!formDisabled) {
          if (stackerType !== null && stackerType > 10 && stackerType < 19) {
            result = await addTempAfterSalesNeedInfoEx({
              userId: values.userId.value,
              driveName: values.driveName,
              // isProduction: values.isProduction,
              // plcType: values.plcType,
              // vm: values.vm,
              hmiType: values.hmiType,
              trackLength: values.trackLength,
              liftingHeight: values.liftingHeight,
              forkOutLength: values.forkOutLength,
              stackerType: stackerType,
              stackerWeight: values.stackerWeight,
              platformWeight: values.platformWeight,
              loadWeight: values.loadWeight,
              plcType: values.plcType,
              vm: values.vm,
              licenseOrderNum: values.licensOrderId.label,
              licenseCount: values.licenseCount,
              stackerShaftInfoExes: dataSourceTwo,
            });
          } else {
            result = await addTempAfterSalesNeedInfoEx({
              userId: values.userId.value,
              driveName: values.driveName,
              isProduction: values.isProduction,
              plcType: values.plcType,
              vm: values.vm,
              stackerType: stackerType,
              licenseOrderNum: values.licensOrderId.label,
              licenseCount: values.licenseCount,
              shaftInfoExDtoList: dataSourceTwo,
            });
          }
        } else {
          // 更新
          if (stackerType !== null && stackerType > 10 && stackerType < 19) {
            result = await updateTempAfterSalesNeedInfoEx({
              id: location.query.id,
              userId: values.userId.value,
              driveName: values.driveName,
              // isProduction: values.isProduction,
              // plcType: values.plcType,
              // vm: values.vm,
              hmiType: values.hmiType,
              stackerType: stackerType,
              trackLength: values.trackLength,
              liftingHeight: values.liftingHeight,
              forkOutLength: values.forkOutLength,
              stackerWeight: values.stackerWeight,
              platformWeight: values.platformWeight,
              loadWeight: values.loadWeight,
              plcType: values.plcType,
              vm: values.vm,
              licenseOrderNum: values.licensOrderId.label,
              licenseCount: values.licenseCount,
              stackerShaftInfoExes: dataSourceTwo,
            });
          } else {
            result = await updateTempAfterSalesNeedInfoEx({
              id: location.query.id,
              userId: values.userId.value,
              stackerType: stackerType,
              driveName: values.driveName,
              isProduction: values.isProduction,
              plcType: values.plcType,
              vm: values.vm,
              licenseOrderNum: values.licensOrderId.label,
              licenseCount: values.licenseCount,
              shaftInfoExDtoList: dataSourceTwo,
            });
          }
        }
        if (result !== null && result !== undefined) {
          message.success('添加成功');

          history.push({
            pathname: `/sales/salesNeedInfoCustomer`,
          });
        }
      } catch {
        // console.log
      }
      console.log('临时保存=====');
    });

    // const values = formRef.current?.getFieldsFormatValue?.();
  };
  const onFinishFailed = (errorInfo: any) => {
    setError(errorInfo.errorFields);
  };

  /**
   * 穿梭框的数据设置
   */

  return (
    <PageHeaderWrapper title={false} breadcrumb={undefined}>
      <ProCard split="vertical">
        <ProCard title="总流程" colSpan="15%" collapsible>
          <Steps size="small" direction="vertical" current={detailStatus}>
            <Step title="新建登记" />
            <Step title="保存" />
            <Step title="提交" />
            <Step title="工程师正在处理" />
            <Step title="需求修改" />
            <Step title="工程师处理完成" />
            <Step title="软件包可以下载" />
            {/* <Step title="调试中" /> */}
          </Steps>
        </ProCard>

        <ProCard
          title="详细内容"
          colSpan="80%"
          tabs={{
            type: 'card',
          }}
        >
          {access.canEngineer() || access.canAdmin() || access.canAdmin() ? (
            <ProCard.TabPane key="tab1" tab="工程师处理流程">
              <Card
                title="工程师步骤处理"
                className={styles.card}
                bordered={true}
                hidden={access.canCustomer()}
                extra={
                  location.query.id !== undefined && location.query.id !== null
                    ? [
                        <Button
                          htmlType="button"
                          type="primary"
                          key="1"
                          onClick={() => {
                            setRoleUserTitle('主任工程师');
                            setRoleUserVisit(true);
                            form.resetFields();
                          }}
                        >
                          指派主任工程师
                        </Button>,

                        <Button
                          htmlType="button"
                          style={{ marginLeft: 20 }}
                          type="primary"
                          key="2"
                          onClick={() => {
                            setRoleUserTitle('工程师');
                            setRoleUserVisit(true);
                            form.resetFields();
                          }}
                        >
                          指派工程师
                        </Button>,
                      ]
                    : []
                }
              >
                <Row gutter={16}>
                  <Steps size="small" current={engineerStatus}>
                    <Step title="未指派" description={assignDesc} />
                    <Step title="主任工程师" description={chiefEngineerDesc} />
                    <Step title="工程师" description={engineerDesc} />
                  </Steps>
                </Row>
              </Card>
              <Modal
                title={roleUserTitle}
                visible={roleUserVisit}
                onOk={handleSubmit2}
                confirmLoading={confirmLoading}
                onCancel={() => setRoleUserVisit(false)}
              >
                <Form
                  name="wrap"
                  labelCol={{ flex: '110px' }}
                  labelAlign="left"
                  labelWrap
                  form={form}
                  wrapperCol={{ flex: 1 }}
                  colon={false}
                >
                  <Form.Item label="工程师信息" name="engineerId">
                    <DebounceSelect
                      showSearch
                      placeholder="Select customers"
                      fetchOptions={(value) => {
                        if (roleUserTitle == '主任工程师') {
                          return roleUsers(value, 'ROLE_004');
                        } else {
                          return roleUsers(value, 'ROLE_002');
                        }
                      }}
                      onChange={(newValue) => {
                        // setValue(newValue as UserValue[]);
                      }}
                      style={{ width: '100%' }}
                    />
                  </Form.Item>
                </Form>
              </Modal>
            </ProCard.TabPane>
          ) : (
            <ProCard.TabPane key="tab1" tab="工程师处理流程">
              {' '}
            </ProCard.TabPane>
          )}

          <ProCard.TabPane key="tab2" tab="填写基本信息">
            <ProForm
              submitter={{
                render: (props, dom) => {
                  if (
                    access.aperatorFilter('salesCreateAndSave') &&
                    location.query.status !== 5 &&
                    !engineerDisabled
                  ) {
                    return (
                      <FooterToolbar>
                        {dom}
                        <Button htmlType="button" key="edit" onClick={onTempSave}>
                          保存
                        </Button>
                      </FooterToolbar>
                    );
                  }
                },
              }}
              formRef={formRef}
              onValuesChange={(changeValues) => {
                if (changeValues.stackerType !== null && changeValues.stackerType !== undefined) {
                  setStackerType(changeValues.stackerType);
                }
                if (
                  changeValues.stackerType !== null &&
                  changeValues.stackerType !== undefined &&
                  changeValues.stackerType > 10 &&
                  changeValues.stackerType < 19
                ) {
                  formRef.current?.setFieldsValue({
                    vm: 3,
                  });
                }
                if (
                  changeValues.stackerType !== null &&
                  changeValues.stackerType !== undefined &&
                  changeValues.stackerType > 0 &&
                  changeValues.stackerType < 9
                ) {
                  formRef.current?.setFieldsValue({
                    vm: 1,
                  });
                }
                // console.log(changeValues.stackerType, '===changeValues.stackerType==');
              }}
              initialValues={formInit}
              layout={formLayoutType}
              grid={grid}
              rowProps={{
                gutter: [16, formLayoutType === 'inline' ? 16 : 0],
              }}
              onFinish={onFinish}
              // onFinishFailed={onFinishFailed}
            >
              <ProCard className={styles.card} bordered={false}>
                <ProFormGroup
                  title="用户信息"
                  extra={
                    <Button
                      htmlType="button"
                      type="primary"
                      key="edit"
                      onClick={() => {
                        if (stackerType !== null && stackerType > 10 && stackerType < 19) {
                          afterSalesDetailExport({ id: location.query.id }).then((res) => {
                            const aLink = document.createElement('a');
                            document.body.appendChild(aLink);
                            aLink.style.display = 'none';
                            aLink.href = window.URL.createObjectURL(res);
                            aLink.setAttribute(
                              'download',
                              `堆垛机版设备信息登记表${new Date()}.xlsx`,
                            );
                            aLink.click();
                            document.body.removeChild(aLink);
                          });
                        } else {
                          afterSalesDetailExport({ id: location.query.id }).then((res) => {
                            const aLink = document.createElement('a');
                            document.body.appendChild(aLink);
                            aLink.style.display = 'none';
                            aLink.href = window.URL.createObjectURL(res);
                            aLink.setAttribute(
                              'download',
                              `基本版设备信息登记表${new Date()}.xlsx`,
                            );
                            aLink.click();
                            document.body.removeChild(aLink);
                          });
                        }
                      }}
                    >
                      导出详情
                    </Button>
                  }
                >
                  <ProFormSelect
                    initialValue={
                      formAdd
                        ? { label: currentUser?.name, value: currentUser?.id }
                        : { label: user.name, value: user.id }
                    }
                    disabled
                    colProps={{ md: 12, xl: 8 }}
                    fieldProps={{
                      labelInValue: true,
                      //这里使用了select的onChange方法，必须使用这样的写法来进行调用onChange方法
                      onChange: (val, val2) => {
                        formRef?.current?.setFieldsValue({
                          address: val2?.object?.loginName,
                          phone: val2?.object?.phone,
                        });
                      },
                    }}
                    debounceTime={1000}
                    name="userId"
                    label="用户名"
                    showSearch
                    request={async (para) => {
                      const result = await userList({ blurry: para.keyWords });
                      return result.data.map((item) => {
                        return { label: item.name, value: item.id, object: item };
                      });
                    }}
                  />

                  <ProFormSelect
                    rules={[
                      {
                        required: true,
                        message: '请输入订货号',
                      },
                    ]}
                    colProps={{ md: 12, xl: 8 }}
                    fieldProps={{
                      labelInValue: true,
                      //这里使用了select的onChange方法，必须使用这样的写法来进行调用onChange方法
                      onChange: (val, val2) => {
                        // formRef?.current?.setFieldsValue({
                        //   address: val2?.object?.loginName,
                        //   phone: val2?.object?.phone,
                        // });
                        // console.log(val, val2);
                      },
                    }}
                    debounceTime={1000}
                    disabled={formDisabled}
                    name="licensOrderId"
                    label="订货号"
                    showSearch
                    request={async (para) => {
                      const result = await licenseOrderList({ blurry: para.keyWords });
                      return result.data.map((item) => {
                        return { label: item.licenseOrderNum, value: item.id, object: item };
                      });
                    }}
                  />
                  <ProFormSelect
                    // options={[
                    //   {
                    //     value: 'chapter',
                    //     label: '盖章后生效',
                    //   },
                    // ]}
                    fieldProps={{
                      //这里使用了select的onChange方法，必须使用这样的写法来进行调用onChange方法
                      onChange: (val, val2) => {
                        console.log(val, val2);
                      },
                    }}
                    disabled={formDisabled}
                    colProps={{ md: 12, xl: 6 }}
                    initialValue={formAdd ? 1 : null}
                    name="stackerType"
                    label="设备类型"
                    options={[
                      { label: '基础版本', value: 1 },
                      { label: '堆垛机:单立柱-单载', value: 11 },
                      { label: '堆垛机:双立柱-单载', value: 12 },
                      { label: '堆垛机:双立柱-双载', value: 13 },
                      { label: '堆垛机:转弯堆垛机', value: 14 },
                      { label: '堆垛机:其它', value: 15 },
                    ]}
                  />
                  <ProFormDependency name={['stackerType']}>
                    {({ stackerType }) => {
                      if (stackerType > 10 && stackerType < 19) {
                        return (
                          <ProFormDigit
                            label="授权号数量"
                            name="licenseCount"
                            colProps={{ md: 12, xl: 8 }}
                            disabled
                            initialValue={1}
                            rules={[
                              {
                                required: true,
                                message: '请输入授权号数量',
                              },
                            ]}
                            // rules={[{ required: true, message: '请输入用户地址' }]}
                            placeholder="授权号数量"
                          />
                        );
                      } else {
                        return (
                          <ProFormDigit
                            label="授权号数量"
                            name="licenseCount"
                            colProps={{ md: 12, xl: 8 }}
                            rules={[
                              {
                                required: true,
                                message: '请输入授权号数量',
                              },
                            ]}
                            // rules={[{ required: true, message: '请输入用户地址' }]}
                            placeholder="授权号数量"
                          />
                        );
                      }
                    }}
                  </ProFormDependency>
                </ProFormGroup>
              </ProCard>

              <ProCard className={styles.card} bordered={false}>
                <ProFormDependency name={['stackerType']}>
                  {({ stackerType }) => {
                    if (stackerType > 10 && stackerType < 19) {
                      return (
                        <ProFormGroup title="设备参数">
                          <ProFormText
                            label="设备名称"
                            name="driveName"
                            rules={[
                              {
                                required: true,
                                message: '请输入设备名称',
                              },
                            ]}
                            colProps={{ md: 12, xl: 6 }}
                            disabled={formDisabled}
                          />
                          <ProFormText
                            label="HMI型号"
                            name="hmiType"
                            rules={[
                              {
                                required: true,
                                message: '请输入HMI型号',
                              },
                            ]}
                            colProps={{ md: 12, xl: 6 }}
                            // rules={[{ required: true, message: '请选择' }]}
                          />
                          <ProFormDigit
                            label="轨道长度(m)"
                            name="trackLength"
                            colProps={{ md: 12, xl: 6 }}
                            rules={[
                              {
                                required: true,
                                message: '请输入轨道数据数量',
                              },
                            ]}
                            // rules={[{ required: true, message: '请输入用户地址' }]}
                            placeholder="授权号数量"
                          />
                          <ProFormDigit
                            label="提升高度(m)"
                            name="liftingHeight"
                            colProps={{ md: 12, xl: 6 }}
                            rules={[
                              {
                                required: true,
                                message: '请输入提升高度',
                              },
                            ]}
                            // rules={[{ required: true, message: '请输入用户地址' }]}
                            placeholder="授权号数量"
                          />
                          <ProFormDigit
                            label="货叉伸出长度(m)"
                            name="forkOutLength"
                            colProps={{ md: 12, xl: 6 }}
                            rules={[
                              {
                                required: true,
                                message: '请输入货叉伸出长度',
                              },
                            ]}
                            // rules={[{ required: true, message: '请输入用户地址' }]}
                            placeholder="货叉伸出长度"
                          />
                          <ProFormDigit
                            label="堆垛机重量(kg)"
                            name="stackerWeight"
                            colProps={{ md: 12, xl: 6 }}
                            rules={[
                              {
                                required: true,
                                message: '请输入堆垛机重量',
                              },
                            ]}
                            // rules={[{ required: true, message: '请输入用户地址' }]}
                            placeholder="堆垛机重量"
                          />

                          <ProFormDigit
                            label="载货台重量(kg)"
                            name="platformWeight"
                            colProps={{ md: 12, xl: 6 }}
                            rules={[
                              {
                                required: true,
                                message: '请输入载货台重量',
                              },
                            ]}
                            // rules={[{ required: true, message: '请输入用户地址' }]}
                            placeholder="载货台重量"
                          />

                          <ProFormDigit
                            label="负载重量(kg)"
                            name="loadWeight"
                            colProps={{ md: 12, xl: 6 }}
                            rules={[
                              {
                                required: true,
                                message: '请输入负载重量',
                              },
                            ]}
                            // rules={[{ required: true, message: '请输入用户地址' }]}
                            placeholder="负载重量"
                          />

                          <ProFormSelect
                            // options={[
                            //   {
                            //     value: 'chapter',
                            //     label: '盖章后生效',
                            //   },
                            // ]}
                            fieldProps={{
                              //这里使用了select的onChange方法，必须使用这样的写法来进行调用onChange方法
                              onChange: (val, val2) => {
                                console.log(val, val2);
                              },
                            }}
                            colProps={{ md: 12, xl: 6 }}
                            initialValue={formAdd ? 3 : null}
                            name="vm"
                            label="行业"
                            options={[
                              { label: '电子', value: 1 },
                              { label: '电池', value: 2 },
                              { label: '物流', value: 3 },
                              { label: '汽车', value: 4 },
                              { label: '太阳能', value: 5 },
                              { label: '增材制造', value: 6 },
                              { label: '包装', value: 7 },
                              { label: '食品饮料', value: 8 },
                              { label: '金属加工', value: 9 },
                              { label: '其他', value: 10 },
                            ]}
                          />

                          <ProFormSelect
                            fieldProps={{
                              //这里使用了select的onChange方法，必须使用这样的写法来进行调用onChange方法
                              onChange: (val, val2) => {
                                console.log(val, val2);
                              },
                            }}
                            colProps={{ md: 12, xl: 6 }}
                            initialValue={formAdd ? 1 : null}
                            name="plcType"
                            label="PLC类型"
                            options={[
                              { label: 'S7-1500', value: 1 },
                              { label: 'S7-1200', value: 0 },
                            ]}
                          />
                        </ProFormGroup>
                      );
                    } else {
                      return (
                        <ProFormGroup title="驱动参数列表">
                          <ProFormText
                            label="设备名称"
                            name="driveName"
                            rules={[{ required: true, message: '请输入设备名称' }]}
                            colProps={{ md: 12, xl: 6 }}
                            disabled={formDisabled}
                            // rules={[{ required: true, message: '请选择' }]}
                          />

                          <ProFormSelect
                            // options={[
                            //   {
                            //     value: 'chapter',
                            //     label: '盖章后生效',
                            //   },
                            // ]}
                            fieldProps={{
                              //这里使用了select的onChange方法，必须使用这样的写法来进行调用onChange方法
                              onChange: (val, val2) => {
                                console.log(val, val2);
                              },
                            }}
                            colProps={{ md: 12, xl: 6 }}
                            initialValue={formAdd ? 1 : null}
                            name="vm"
                            label="行业"
                            options={[
                              { label: '电子', value: 1 },
                              { label: '电池', value: 2 },
                              { label: '物流', value: 3 },
                              { label: '汽车', value: 4 },
                              { label: '太阳能', value: 5 },
                              { label: '增材制造', value: 6 },
                              { label: '包装', value: 7 },
                              { label: '食品饮料', value: 8 },
                              { label: '金属加工', value: 9 },
                              { label: '其他', value: 10 },
                            ]}
                          />

                          <ProFormSelect
                            fieldProps={{
                              //这里使用了select的onChange方法，必须使用这样的写法来进行调用onChange方法
                              onChange: (val, val2) => {
                                console.log(val, val2);
                              },
                            }}
                            colProps={{ md: 12, xl: 6 }}
                            initialValue={formAdd ? 1 : null}
                            name="isProduction"
                            label="是否量产"
                            options={[
                              { label: '是', value: 1 },
                              { label: '否', value: 0 },
                            ]}
                          />

                          <ProFormSelect
                            fieldProps={{
                              //这里使用了select的onChange方法，必须使用这样的写法来进行调用onChange方法
                              onChange: (val, val2) => {
                                console.log(val, val2);
                              },
                            }}
                            colProps={{ md: 12, xl: 6 }}
                            initialValue={formAdd ? 1 : null}
                            name="plcType"
                            label="PLC类型"
                            options={[
                              { label: 'S7-1500', value: 1 },
                              { label: 'S7-1200', value: 0 },
                            ]}
                          />
                        </ProFormGroup>
                      );
                    }
                  }}
                </ProFormDependency>
              </ProCard>
            </ProForm>
          </ProCard.TabPane>
          <ProCard.TabPane key="tab3" tab="轴信息">
            <ProCard className={styles.card} bordered={false}>
              <ProList<any>
                
                actionRef={actionRef}
                metas={{
                  title: {
                    dataIndex: 'index',
                    valueType: 'index',
                  },

                  subTitle: {
                    dataIndex: 'shaftName',
                    render: (text, row) => {
                      return <Tag color="#5BD8A6"> {row.shaftName}</Tag>;
                    },
                  },

                  description: {
                    dataIndex: 'index',
                    render: (_, row) => {
                      if (stackerType > 10 && stackerType < 19) {
                        return <SalesNeedInfoDescription row={row} actionRef={actionRef} isStacker={true} />
                      } else {
                        return <SalesNeedInfoDescription row={row} actionRef={actionRef} isStacker={false} />
                      }
                      
                    },
                  },

                  content: {},
                  actions: {
                    render: (text, row) => [
                      <a
                        href={row.html_url}
                        target="_blank"
                        rel="noopener noreferrer"
                        key="link"
                        onClick={() => {
                          setAxiosCreate(false);
                          setDriveCommonVis(true);
                          setValues({ ...row, stackerType: stackerType });
                        }}
                      >
                        编辑
                      </a>,
                      <a
                        href={row.html_url}
                        target="_blank"
                        rel="noopener noreferrer"
                        key="warning"
                        onClick={() => {
                          let addone = {};
                          dataSourceTwo
                            .filter((item) => item.id == row.id)
                            .map((item) => {
                              addone = { ...item };
                            });
                          addone.id = (Math.random() * 1000000).toFixed(0);
                          console.log(addone, '---addOne---');
                          setDataSourceTwo([...dataSourceTwo, addone]);
                          actionRef.current.reload();
                        }}
                      >
                        复制
                      </a>,
                      <a
                        href={row.html_url}
                        target="_blank"
                        rel="noopener noreferrer"
                        key="view"
                        onClick={() => {
                          setDataSourceTwo(dataSourceTwo.filter((item) => item.id !== row.id));
                          actionRef.current.reload();
                        }}
                      >
                        删除
                      </a>,
                    ],
                  },
                  driveType: {
                    title: '驱动类型',
                    valueType: 'select',
                    dataIndex: 'driveType',
                    valueEnum: {
                      1: { text: 'V90', status: 'Default' },
                      2: {
                        text: 'S210',
                        status: 'success',
                      },
                      // 0: {
                      //   text: '第三方',
                      //   status: 'warning',
                      // },
                    },
                  },
                }}
                toolBarRender={() => [
                  <Button
                    key="button"
                    icon={<PlusOutlined />}
                    onClick={() => {
                      if (stackerType > 10 && stackerType < 19) {
                        SetStackerShowUploadFile(true);
                      } else {
                        SetShowUploadFile(true);
                      }
                      // console.log(selectedRows, '---选取多行----');
                      // 1.清空form
                    }}
                    type="primary"
                  >
                    上传轴信息
                  </Button>,
                  <Button
                    key="button"
                    icon={<PlusOutlined />}
                    onClick={() => {
                      // console.log(selectedRows, '---选取多行----');
                      // 1.清空form
                      setDriveCommonVis(true);
                      setValues({ stackerType: stackerType });
                      setAxiosCreate(true);
                    }}
                    type="primary"
                  >
                    新建轴
                  </Button>,
                  <Button
                    key="button"
                    icon={<PlusOutlined />}
                    onClick={() => {
                      if (stackerType > 10 && stackerType < 19) {
                        downloadTemplateByName({ fileName: '堆垛机版电机上传模板.xlsx' }).then(
                          (res) => {
                            const aLink = document.createElement('a');
                            document.body.appendChild(aLink);
                            aLink.style.display = 'none';
                            aLink.href = window.URL.createObjectURL(res);
                            aLink.setAttribute('download', `堆垛机版电机上传模板.xlsx`);
                            aLink.click();
                            document.body.removeChild(aLink);
                          },
                        );
                      } else {
                        downloadTemplateByName({ fileName: '基本版电机上传模板.xlsx' }).then(
                          (res) => {
                            const aLink = document.createElement('a');
                            document.body.appendChild(aLink);
                            aLink.style.display = 'none';
                            aLink.href = window.URL.createObjectURL(res);
                            aLink.setAttribute('download', `基本版电机上传模板.xlsx`);
                            aLink.click();
                            document.body.removeChild(aLink);
                          },
                        );
                      }
                    }}
                    type="primary"
                  >
                    下载上传模板
                  </Button>,
                ]}
                rowKey="id"
                name="axios"
                onRow={(record: any) => {
                  return {
                    onMouseEnter: () => {},
                    onClick: () => {},
                  };
                }}
                itemLayout="horizontal"
                headerTitle="轴信息列表"
                rowSelection={rowSelection}
                dataSource={dataSourceTwo}
                expandable={{ expandedRowKeys, onExpandedRowsChange: setExpandedRowKeys }}
              />
              <DriveParaCalcCommon
                visible={driveCommonVis}
                title="驱动参数预览"
                disable={false}
                values={values}
                ref={driveRef}
                initialValues={values}
                isDriveParaCalc={false}
                onCancel={() => {
                  console.log(values, '---values---');
                  actionRef.current.reload();
                  setDriveCommonVis(false);
                }}
                onOk={() => {
                  console.log(values, '---values---');
                  const result = driveRef.current.getFieldsValue();
                  console.log(result, '---result---');
                  if (axiosCreate) {
                    result.id = (Math.random() * 1000000).toFixed(0);
                    setDataSourceTwo([...dataSourceTwo, result]);
                  } else {
                    if (result.id !== null && result.id !== undefined) {
                      for (let i = 0; i < dataSourceTwo.length; i++) {
                        if (dataSourceTwo[i].id === result.id) {
                          Object.assign(dataSourceTwo[i], result);
                        }
                      }
                      // dataSourceTwo
                      //   .filter((item) => item.id === result.id)
                      //   .map((item) => {
                      //     return { ...result, ...item };
                      //   });
                      console.log(dataSourceTwo, '---dataSourceTwo---');
                      setDataSourceTwo(dataSourceTwo);
                    }
                  }
                  actionRef.current.reload();
                  setDriveCommonVis(false);
                }}
              />
              <UploadFile
                visible={showUploadFile}
                tableHeader={columns}
                errorStatus={errorStatus}
                onOk={(tables, tableHeader) => {
                  console.log(errorStatus, '---errorStatus---');
                  if (errorStatus || !checked) {
                    message.error('请检查数据无误后提交');
                  } else {
                    setDataSourceTwo(tables);
                    SetErrorStatus(false);
                    console.log(tables, tableHeader, '--tableData---');
                    SetShowUploadFile(false);
                  }
                }}
                onChange={() => {
                  SetErrorStatus(false);
                }}
                onCheck={(tables) => {
                  // tables.map((item) => (item.errorMsg = undefined));
                  let count = 0;
                  console.log(tables, '---onCheck tables---');
                  SetErrorStatus(false);
                  setChecked(true);
                  tables.map((item) => {
                    if (item.driveType === undefined) {
                      SetErrorStatus(true);
                      item.errorMsg = '驱动类型未填';
                    } else if (item.motorOrderNum === undefined) {
                      SetErrorStatus(true);
                      item.errorMsg = '电机订货号未填';
                    } else if (item.loadType === undefined) {
                      SetErrorStatus(true);
                      item.errorMsg = '负载类型未填';
                    } else if (item.mechanicalStructure === undefined) {
                      SetErrorStatus(true);
                      item.errorMsg = '机械结构未填';
                    } else if (item.controlMode === undefined) {
                      SetErrorStatus(true);
                      item.errorMsg = '控制模式未填';
                    } else if (item.commTelegram === '') {
                      SetErrorStatus(true);
                      item.errorMsg = '通讯报文未填';
                    } else if (item.additionalTelegram === '') {
                      SetErrorStatus(true);
                      item.errorMsg = '附加报文未填';
                    } else if (item.motorRotation === '') {
                      SetErrorStatus(true);
                      item.errorMsg = '电机方向未填';
                    } else if (item.controlMode === 1) {
                    } else if (item.controlMode === 2) {
                      if (item.commTelegram !== 111) {
                        // Epos模式
                        console.log('---commTelegram---');
                        SetErrorStatus(true);
                        item.errorMsg = 'Epos模式-通讯报文有误';
                      } else if (item.additionalTelegram !== 999) {
                        SetErrorStatus(true);
                        item.errorMsg = 'Epos模式-附加报文有误';
                      } else if (item.gearRationLoad === '') {
                        SetErrorStatus(true);
                        item.errorMsg = '齿轮比负载(V90 EPOS)未填';
                      } else if (item.gearRationMotor === '') {
                        SetErrorStatus(true);
                        item.errorMsg = '齿轮比电机(V90 EPOS)未填';
                      } else if (item.loadOneTurnDistance === '') {
                        SetErrorStatus(true);
                        item.errorMsg = '负载一圈的距离(V90 EPOS)未填';
                      } else if (item.velocityMax === '') {
                        SetErrorStatus(true);
                        item.errorMsg = '设备最大速度Vmax(V90 EPOS)未填';
                      } else if (item.increaseTimeEpos === '') {
                        SetErrorStatus(true);
                        item.errorMsg = '0-Vmax时间(V90 EPOS)未填';
                      } else if (item.decreaseTimeEpos === '') {
                        SetErrorStatus(true);
                        item.errorMsg = 'Vmax-0时间(V90 EPOS)未填';
                      } else {
                        console.log('---no mistake---');
                        count += 1;
                      }
                    } else {
                    }

                    return item;
                  });

                  if (count === tables.length) {
                    SetErrorStatus(false);
                    message.success('数据经检验无误');
                  }
                  return tables;
                }}
                onCancel={() => {
                  SetShowUploadFile(false);
                }}
                title="excel预览"
              />
              <UploadFile
                visible={stackerShowUploadFile}
                tableHeader={stackerColumns}
                errorStatus={errorStatus}
                onOk={(tables, tableHeader) => {
                  // console.log(errorStatus, '---errorStatus---');
                  // if (errorStatus || !checked) {
                  //   message.error('请检查数据无误后提交');
                  // } else {
                  setDataSourceTwo(tables);
                  SetErrorStatus(false);
                  console.log(tables, tableHeader, '--tableData---');
                  SetStackerShowUploadFile(false);
                  // }
                }}
                onChange={() => {
                  SetErrorStatus(false);
                }}
                onCheck={(tables) => {
                  SetErrorStatus(false);
                  setChecked(true);
                  return tables;
                }}
                onCancel={() => {
                  SetStackerShowUploadFile(false);
                }}
                title="excel预览"
              />
            </ProCard>
          </ProCard.TabPane>
        </ProCard>
      </ProCard>
    </PageHeaderWrapper>
  );
};

export default SalesNeedInfoDetail;
